package com.epam.qanda.db.mapping;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import com.epam.qanda.db.annotaion.DBFieldName;

public class Converter {
	public static <T> T fromResaultSetToObject(ResultSet rs, Class<T> cls)
			throws SQLException {
		T obj = null;
		try {
			obj = cls.newInstance();
		} catch (InstantiationException | IllegalAccessException e1) {
			e1.printStackTrace();
		}
		ResultSetMetaData rsmd = rs.getMetaData();
		int columtCount = rsmd.getColumnCount();
		Field[] fields = cls.getDeclaredFields();
		for (int i = 1; i <= columtCount; i++) {
			String columnName = rsmd.getColumnName(i);
			for (int j = 0; j < fields.length; j++) {
				if (fields[j].getName().equals("serialVersionUID"))
					continue;

				if (fields[j].getAnnotation(DBFieldName.class).value()
						.equals(columnName)) {
					fields[j].setAccessible(true);
					try {
						Object tmp = rs.getObject(i);
						fields[j].set(obj, tmp);
					} catch (IllegalArgumentException | IllegalAccessException e) {
						e.printStackTrace();
					}
				}

			}
		}
		return obj;
	}
}
